package org.bjou

import org.apache.shiro.crypto.hash.Sha256Hash
import org.springframework.dao.DataIntegrityViolationException
import org.bjou.*
import java.text.*
import org.springframework.web.multipart.MultipartHttpServletRequest
import org.springframework.web.multipart.commons.CommonsMultipartFile
import java.util.Locale


class UserBaseinfoController {

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]
    
    

    def index() {
        redirect(action: "list", params: params)
    }
    
    //教师信息获取
    def export()
    {
        
        
    }
    
    
    def exportXls() {
        
        def cel = {  
            createAlias('assign', 'c')
            if(params.groupId){  
                eq("userGroup.id", params.groupId.toLong())
            }
           
        }
        //def assignList = UserBaseinfo.createCriteria().list(params,cel) 
        
        log.error "people enter UserBaseinfoController action exportXls"  
        // using with list of parameters
        def assignList =  UserBaseinfo.executeQuery("select u,a from UserBaseinfo u,Assign a where a.userBaseinfo.id = u.id order by u.id ")
        
        def sdf = new SimpleDateFormat("yyyyMMddHHmmss")
        XlsExportService xlsExportService = new XlsExportService();  
        response.setHeader("Content-disposition", "attachment; filename="+sdf.format(new Date())+".xls")
        response.setContentType("application/vnd.ms-excel")
        xlsExportService.assignExport(response.outputStream, assignList)


    }

    //教师简历查看
    def list() {
        params.max = Math.min(params.max ? params.int('max') : 10, 100)
        def cel = {  
            if(params.fullname){  
                like("fullname", "%${params.fullname}%")  
            }
            if(params.groupId){  
                eq("userGroup.id", params.groupId.toLong())
            }
            
        }  
        def groupList = UserBaseinfo.createCriteria().list(params,cel) 
        
        [userBaseinfoInstanceList: groupList, userBaseinfoInstanceTotal: groupList.totalCount]
    }
    
    //教师分组
    def group() {
        params.max = Math.min(params.max ? params.int('max') : 10, 100)
        
        def cel = {  
            if(params.fullname){  
                like("fullname", "%${params.fullname}%")  
            }
            if(params.groupId){  
                eq("userGroup.id", params.groupId.toLong())
            }
            
        }  
        def groupList = UserBaseinfo.createCriteria().list(params,cel) 
        [userBaseinfoInstanceList: groupList, userBaseinfoInstanceTotal: groupList.totalCount]
    }
    
    
    def saveGroup() {
        def currentTerm = Config.findByConfigKey('currentTerm')?.configValue
        //TODO 判断分校角色应该放到Login里面
        print params
       
            
        params.groupUser.each {
            def userBaseinfoInstance = UserBaseinfo.findById(it)
            userBaseinfoInstance.setUserGroup(UserGroup.get(params.groupId))
            // userBaseinfoInstance.userGroup.id = params.groupId
            //print userBaseinfoInstance.userGroup.id
            userBaseinfoInstance.save(flush: true)
             
        }
        flash.message="成功更新了教师的分组"
        redirect(action: "group")
       
        
    }

    def create() {
        [userBaseinfoInstance: new UserBaseinfo(params)]
    }

    def save() {
        def userBaseinfoInstance = new UserBaseinfo(params)
        if (!userBaseinfoInstance.save(flush: true)) {
            render(view: "create", model: [userBaseinfoInstance: userBaseinfoInstance])
            return
        }

        flash.message = message(code: 'default.created.message', args: [message(code: 'userBaseinfo.label', default: 'UserBaseinfo'), userBaseinfoInstance.id])
        redirect(action: "show", id: userBaseinfoInstance.id)
    }
    
   
    //前台注册
    def reg() {
        
        //校验邮箱
        if(ShiroUser.findByUsername(params.email.toString())!=null)
        {
            flash.message = "你注册的邮箱已存在"
            redirect(controller:"Auth", action: "reg")
            return
        }
        //ID card
        if(UserBaseinfo.findByIdCard(params.idCard.toString())!=null)
        {
            flash.message = "你注册的身份证已存在"
            redirect(controller:"Auth", action: "reg")
            return
        }
        
        
        def userBaseinfoInstance = new UserBaseinfo(params)
        //添加一个用户，邮箱作为用户名，身份证作为密码,角色为教师
        def regUser = new ShiroUser(username: params.email.toString(), passwordHash: new Sha256Hash(params.idCard.toString()).toHex()) 
        regUser.addToRoles(ShiroRole.findByName('教师'))
        regUser.save() 
       
        
        userBaseinfoInstance.setUser(regUser)
        
        if (!userBaseinfoInstance.save(flush: true)) {
            
            redirect(controller:"Auth", action: "reg", model: [userBaseinfoInstance: userBaseinfoInstance])
            //render(view: "create", model: [userBaseinfoInstance: userBaseinfoInstance])
            return
        }
        
        
        //flash.message = message(code: 'default.created.message', args: [message(code: 'userBaseinfo.label', default: 'UserBaseinfo'), userBaseinfoInstance.id])
       
        flash.message = "注册成功！"
        
           
        session.user = regUser
       
        def role = ShiroRole.findByUser(regUser.id).list().get(0)
        session.role = role
        
        params.username =  params.email
        params.password = params.idCard
        params.message =   "注册成功。请牢记你的用户名为注册的邮箱，密码为注册填写的身份证号。"
        
        params.targetUri = "/UserBaseinfo/edit/"+userBaseinfoInstance.id.toString()
        //flash.message = "注册成功。请牢记你的用户名为注册的邮箱，密码为注册填写的身份证号。"
        redirect(controller:"Auth", action: "signIn" ,params: params)
    }

    def show() {
        def userBaseinfoInstance = UserBaseinfo.get(params.id.toLong())
        if (!userBaseinfoInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'userBaseinfo.label', default: 'UserBaseinfo'), params.id])
            redirect(action: "list")
            return
        }

        [userBaseinfoInstance: userBaseinfoInstance]
    }

    def edit() {
        
        def userBaseinfoInstance
        
        if(!params.id)
        {
            println "1"
            userBaseinfoInstance = UserBaseinfo.findByUser(session.user)
        }
        else
        {
            println "2"
            userBaseinfoInstance = UserBaseinfo.get(params.id)
        }
         if (!userBaseinfoInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'userBaseinfo.label', default: 'UserBaseinfo'), params.id])
            redirect(action: "list")
            return
        }
       
            
       
        def userResumes = UserResume.findAllByUserBaseinfo(userBaseinfoInstance)
        def userAttachs = UserAttach.findAllByUserBaseinfo(userBaseinfoInstance)
        def yearList=[]
        for(i in 1970..<2020)  
        {  
           yearList.add(i)
        }
        
        def monthList=[]
        for(i in 1..12)  
        {  
           monthList.add(i)
        }  
        
        
        
       
       
         

        [userBaseinfoInstance: userBaseinfoInstance,userResumes:userResumes,userAttachs:userAttachs,yearList:yearList,monthList:monthList]
    }

    def update() {
        def userBaseinfoInstance = UserBaseinfo.get(params.id)
        if (!userBaseinfoInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'userBaseinfo.label', default: 'UserBaseinfo'), params.id])
            redirect(action: "list")
            return
        }

        if (params.version) {
            def version = params.version.toLong()
            if (userBaseinfoInstance.version > version) {
                userBaseinfoInstance.errors.rejectValue("version", "default.optimistic.locking.failure",
                    [message(code: 'userBaseinfo.label', default: 'UserBaseinfo')] as Object[],
                          "Another user has updated this UserBaseinfo while you were editing")
                render(view: "edit", model: [userBaseinfoInstance: userBaseinfoInstance])
                return
            }
        }

        userBaseinfoInstance.properties = params
        
        
        if(request instanceof MultipartHttpServletRequest) {
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
            CommonsMultipartFile file = (CommonsMultipartFile)multiRequest.getFile("avatar");
            userBaseinfoInstance.avatar = file.bytes // screenshot is the image blob field of the record
        }

        //check teacher flag
        //基本信息至少包含：姓名，性别，生日，身份证号，手机号，电子邮箱，职级。
        //教育经历至少包含：学习时间，毕业学校，所学专业，最后学历
        if(userBaseinfoInstance.fullname&&userBaseinfoInstance.gentle&&userBaseinfoInstance.birthday&&userBaseinfoInstance.idCard&&userBaseinfoInstance.mobile&&userBaseinfoInstance.email&&userBaseinfoInstance.title)
        {
            if(userBaseinfoInstance.school&&userBaseinfoInstance.degree&&userBaseinfoInstance.majorName)
            {
                userBaseinfoInstance.teacherFlag = 1
            }
        }
        
        

        if (!userBaseinfoInstance.save(flush: true)) {
            render(view: "edit", model: [userBaseinfoInstance: userBaseinfoInstance])
            return
        }

        flash.message ="个人信息更新成功"
        redirect(action: "show", id: userBaseinfoInstance.id)
    }
    
    //显示图片
    def viewImage() {

        def userBaseinfoInstance = UserBaseinfo.get(params.id.toLong())
      
        println  userBaseinfoInstance.avatar
        def image = userBaseinfoInstance.avatar
        response.contentType = 'image/jpeg' // or the appropriate image content type
        response.outputStream << image
        response.outputStream.flush()
      
          
        
       

    } 

    def delete() {
        def userBaseinfoInstance = UserBaseinfo.get(params.id)
        if (!userBaseinfoInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'userBaseinfo.label', default: 'UserBaseinfo'), params.id])
            redirect(action: "list")
            return
        }

        try {
            userBaseinfoInstance.delete(flush: true)
            flash.message = message(code: 'default.deleted.message', args: [message(code: 'userBaseinfo.label', default: 'UserBaseinfo'), params.id])
            redirect(action: "list")
        }
        catch (DataIntegrityViolationException e) {
            flash.message = message(code: 'default.not.deleted.message', args: [message(code: 'userBaseinfo.label', default: 'UserBaseinfo'), params.id])
            redirect(action: "show", id: params.id)
        }
    }
    
    
    //无课程教师查询
    def noCourseList() {
        
        println params
        def currentTerm = Config.findByConfigKey('currentTerm')?.configValue
        
        if (!params.max) params.max = 20  
        if (!params.offset) params.offset = 0  
        if (!params.sort) params.sort = "id"  
        if (!params.order) params.order = "asc"  
          
        def cel = {
            
           
            if(params.groupId){  
                eq("userGroup.id", params.groupId.toLong())  
            }
            // createAlias('UserBaseinfo', 'u')
            //createAlias('course', 'c', CriteriaSpecification.LEFT_JOIN)
            //教师
            sqlRestriction ("user_id in(select shiro_user_id from shiro_user_roles where shiro_role_id = 7)" )
            //sqlRestriction ("user_id not in(select distinct user_id from course where current_term = '"+currentTerm+"')" )
           
        }  
        
        
        //        from user_baseinfo u left join course c on u.user_id = c.user_id
        //where 1=1 
        //and u.user_id in(select shiro_user_id from shiro_user_roles where shiro_role_id = 7)
        //and c.course_name is  null
        
        def noCourseList = UserBaseinfo.createCriteria().list(params,cel) 
        
        // def courseList = Course.findAll("from Course where id in(select course.id from BranchCourse)")
       
        
        
        [userBaseinfoInstanceList: noCourseList, userBaseinfoInstanceTotal: noCourseList.totalCount,currentTerm:currentTerm]
    }
    
    
    //聘任情况查询
    def assignList() {
        
        
        //        sql=select t.fullname,t.group_name,sum(cnt)
        //from 
        //(
        //select u.fullname,g.group_name ,case when c.course_name is not null then 1 else 0 end as cnt from user_baseinfo u 
        //left join course c on u.user_id = c.user_id
        //inner join user_group g on u.user_group_id = g.id
        //where 1=1 and u.user_id in(select shiro_user_id from shiro_user_roles where shiro_role_id = 7)
        //) t
        //GROUP BY t.fullname,t.group_name
        
        println params
        def currentTerm = Config.findByConfigKey('currentTerm')?.configValue
        
        if (!params.max) params.max = 20  
        if (!params.offset) params.offset = 0  
        if (!params.sort) params.sort = "id"  
        if (!params.order) params.order = "asc"  
          
        def cel = {
            if(params.groupId){  
                eq("userGroup.id", params.groupId.toLong())  
            }
            sqlRestriction ("user_id in(select shiro_user_id from shiro_user_roles where shiro_role_id = 7)" )
          
            
        }  
        
        def courseList = UserBaseinfo.createCriteria().list(params,cel) 
        
        def assignList=[]
        courseList.each{ ch ->
            def chJson= [:]
            chJson['id'] = ch.id
            chJson['fullname'] = ch.fullname
            
            
            chJson['cnt'] = Assign.countByUserBaseinfo(ch)
            chJson['groupName'] = ch.userGroup?.groupName
            
            assignList << chJson
        }
        
        print assignList
        [userBaseinfoInstanceList: assignList, userBaseinfoInstanceTotal: courseList.totalCount]
    }
    
    def listByTitle(){
        assert null != params.title
        println params.title
       
        if(params.title)
        {
             
            render g.select(optionKey:"proTitle",optionValue:"proTitle", from:Title.findAllByTitle(params.title), name:"proTitle")
      
        }
        else
        {
            render g.select(optionKey:"proTitle",optionValue:"proTitle", from:Title.findAll(), name:"proTitle")
      
        }
    }
}
